package org.spiderflow.controller;

import org.apache.commons.lang3.StringUtils;
import org.spiderflow.configuration.WebSecurityConfig;
import org.spiderflow.core.model.User;
import org.spiderflow.core.service.UserService;
import org.spiderflow.model.JsonBean;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
public class LoginController {

    @Resource
    private UserService userService;

    @GetMapping("/")
    public ModelAndView index(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String account, Model model) {
        model.addAttribute("name", account);
        return new ModelAndView("index");
    }

    @GetMapping("/login")
    public ModelAndView login() {
        return new ModelAndView("login");
    }



    @RequestMapping(value = "/loginPost", method = RequestMethod.POST)
    public JsonBean login(@ModelAttribute User user, HttpSession session) {
        if(StringUtils.isBlank(user.getUserName())){
            return new JsonBean<>(400, "用户名不能为空！");
        }
        if(StringUtils.isBlank(user.getPassWord())){
            return new JsonBean<>(400, "密码不能为空！");
        }
        User userDB = userService.findByUserNameAndPassWord(user);

        if (userDB==null) {
            return new JsonBean<>(400, "用户名或密码错误！");
        }else {
            session.setAttribute(WebSecurityConfig.SESSION_KEY, user.getUserName());
            return new JsonBean<>(200, "登录成功！");
        }

    }
}

